﻿using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.PB;
using Coldairarrow.Entity.Print;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Coldairarrow.Util.ClassLibrary;
using Coldairarrow.Util.Helper;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_EquipmentBusiness : BaseBusiness<PB_Equipment>, IPB_EquipmentBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        public PB_EquipmentBusiness(IDbAccessor db, IOperator @operator)
            : base(db)
        {
            _operator = @operator;
        }

        #region 外部接口

        public async Task<PageResult<PB_EquipmentDTO>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var search = input.Search;
            Expression<Func<PB_Equipment, Base_Department, PB_Workshop, PB_Station, Base_User,PB_EquipmentDTO>> select = (a, b, c, d,e) => new PB_EquipmentDTO
            {
                DeptName = b.Name,
                WorkshopName = c.Name,
                StationName = d.Name,
                UserName=e.RealName
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.DeptId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Workshop>() on a.WorkshopId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_Station>() on a.StationId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<Base_User>() on a.CustodianId equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d,e);
            if (!search.Keyword.IsNullOrEmpty())
            {
                var keyword = $"%{search.Keyword}%";
                q = q.Where(x =>
                      EF.Functions.Like(x.Name, keyword)
                      || EF.Functions.Like(x.Code, keyword)
                      || EF.Functions.Like(x.StationId, keyword)
                      || EF.Functions.Like(x.Mac, keyword));
            }
            q=q.Where(m => _operator.Property.DeptIds.Contains(m.DeptId));
            return await q.GetPageResultAsync(input);
        }

        public async Task<PB_Equipment> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        [DataAddLog(UserLogType.PDA管理, "Name", "PDA管理")]
        [DataRepeatValidate(new string[] { "Code" }, new string[] { "编号" })]
        public async Task AddDataAsync(PB_Equipment data)
        {
            await InsertAsync(data);
        }

        [DataEditLog(UserLogType.PDA管理, "Name", "PDA管理")]
        [DataRepeatValidate(new string[] { "Code" }, new string[] { "编号" })]
        public async Task UpdateDataAsync(PB_Equipment data)
        {
            await UpdateAsync(data);
        }

        [DataDeleteLog(UserLogType.PDA管理, "Name", "PDA管理")]
        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        public async Task<AjaxResult> SelectEquipmentD(PB_EquipmentPrint data, MongoDBOptions _mongodbOptions)
        {
            try
            {
                List<string> List = new List<string>();
                foreach (var item in data.Equipmentid)
                {
                    List.Add(item);
                }
                var q = GetIQueryable();
                List<PrintQueue> printqueue = new List<PrintQueue>();
                var res = q = q.Where(m => List.Contains(m.Id));
                var k = await Db.GetIQueryable<Base_Department>().Where(m => m.Id == _operator.Property.DepartmentId).FirstOrDefaultAsync();
                foreach (var item in res)
                {
                    PB_Equipment storArea = new PB_Equipment();
                    PrintQueue printdata = new PrintQueue();
                    printdata.Id = IdHelper.GetId();
                    printdata.No = item.Code;//编号
                    printdata.Name = item.Name;
                    printdata.Date = DateTime.Now.ToString();//生产日期当前时间
                    printdata.Dept = k.Name;//当前登录人所在组织
                    printdata.QrCode ="01"+","+item.Id;//设备码
                    printdata.Type = Skill_Type.equipment.ToString();//
                    printdata.Status = "0";
                    printdata.Printer = data.PrintID;
                    printdata.TypeName = item.Code;
                    printdata.IsProduct = false;
                    printdata.Code = item.EquNum;

                    printqueue.Add(printdata);
                }
                MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, printqueue);
                AjaxResult resIn = new AjaxResult
                {
                    Success = true,
                    Msg = "打印成功"
                };
                return resIn;
            }
            catch (Exception)
            {
                AjaxResult res = new AjaxResult
                {
                    Success = false,
                    Msg = "打印失败！数据错误请检查数据"
                };
                return res;
            }
        }

        public  async Task<AjaxResult> CountPrint(PB_EquipmentCountPrint data, MongoDBOptions _mongodbOptions)
        {
            var q = GetIQueryable();
            List<PrintQueue> printqueue = new List<PrintQueue>();
            var list = q;
            var k = await Db.GetIQueryable<Base_Department>().Where(m => m.Id == _operator.Property.DepartmentId).FirstOrDefaultAsync();
            foreach (var item in list) {
                PB_Equipment equipment = new PB_Equipment();
                PrintQueue printdata = new PrintQueue();
                printdata.Id = IdHelper.GetId();//id
                printdata.No = item.Code;//编号
                printdata.Name = item.Name;//PDA，名称
                printdata.Date = DateTime.Now.ToString();//生产日期当前时间
                printdata.Dept = k.Name;//当前登录人所在组织
                printdata.QrCode = "01" + "," + item.Id;//设备码
                printdata.Type = Skill_Type.equipment.ToString();//
                printdata.Status = "0";
                printdata.Printer = data.PrintID;
                printdata.TypeName = item.Code;
                printdata.IsProduct = false;
                printdata.Code = item.EquNum;

                printqueue.Add(printdata);
            }
            MongoDBHelper mogo = new MongoDBHelper(_mongodbOptions);
            throw new NotImplementedException();
        }

        /// <summary>
        /// 获取PDA信息
        /// </summary>
        /// <param name="EquipmentAddress">PDA地址</param>
        /// <returns></returns>
        public async Task<PB_Equipment> GetEquipmentDataAsync(string EquipmentAddress)
        {
            if (!EquipmentAddress.IsNullOrEmpty())
            {
                EquipmentAddress = EquipmentAddress.Replace("，", ",");
            }
            else
            {
                throw new BusException("请获取PDA地址");
            }
            PB_Equipment Equipment = await Db.GetIQueryable<PB_Equipment>().Where(x => x.Route == EquipmentAddress).FirstOrDefaultAsync();
            if (!Equipment.IsNullOrEmpty())
            {
                string Bluetooth = Equipment.Bluetooth;
                if (Bluetooth.IsNullOrEmpty())
                {
                    throw new BusException("设备未绑定蓝牙打印机,可能会造成无法打印,请维护");
                }
                Equipment.Bluetooth = "DD" + Bluetooth.Remove(0, 2);
                return Equipment;
            }
            else
            {
                throw new BusException("设备未绑定蓝牙打印机,可能会造成无法打印,请维护");
            }
        }

        #endregion

        #region 私有成员

        #endregion
    }
}